package com.ktjy.service.impl;

import com.ktjy.service.UploadService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {
    @Value("${file.upload-path}")
    String uploadPath;
    @Value("${file.url}")
    String url;

    @Override
    public String uploadFile(MultipartFile uploadFile) throws IOException {
        //允许上传的文件类型
        String[] allowImageExt = {"jpg", "jpeg", "png", "gif", "bmp"};
        Set<String> include = new HashSet(Arrays.asList(allowImageExt));

        //文件上传的路劲
        if(uploadFile!=null && !uploadFile.isEmpty()){
            //获取上传文件的名称 1.jpg
            String fileName = uploadFile.getOriginalFilename();
            //获取文件的后缀
            String extension = StringUtils.getFilenameExtension(fileName);
            //判断文件类型是否允许上传
            if(!include.contains(extension)){
                throw new RuntimeException("上传文件仅支持" + include + "扩展名！ ");
            }
            //创建新的文件名
            String uploadFileName= UUID.randomUUID()+"."+ extension;
            //上传文件
            //将文件抽象成file对象
            File file=new File(uploadPath,uploadFileName);
            //判断文件所在的目录存不存在
            if(!file.getParentFile().exists()){//如果不存在
                //创建目录
                file.getParentFile().mkdirs();
            }
            //上传操作
            uploadFile.transferTo(file);

            //将文件路劲保存起来
            return url+uploadFileName;
        }
        return null;
    }
}
